﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MotionControl.Modules.PLC.Business
{
    public class BoolList: ObservableCollection<BoolType>
    {
        public static BoolList GetInstance { get => _instance.Value; }

        private static readonly Lazy<BoolList> _instance = new Lazy<BoolList>(() => new BoolList(), true);
        private BoolList() {
            Add(new BoolType("循环模式"));
            Add(new BoolType("背景光源启用"));
            Add(new BoolType("1号鼓风机启动"));
            Add(new BoolType("2号鼓风机启动"));
            Add(new BoolType("1号鼓风机换向阀启动"));
            Add(new BoolType("2号鼓风机换向阀启动"));
            Add(new BoolType("相机升降轴(启用/禁用)"));
            Add(new BoolType("上吸附升降轴(启用/禁用)"));
            Add(new BoolType("1号鼓风机(启用/禁用)"));
            Add(new BoolType("2号鼓风机(启用/禁用)"));
            ReadFromJsonFile();
        }

        private const string jsonFilePath = "data/plc_bools.json";
        public void ReadFromJsonFile()
        {
            try
            {
                string jsonFromFile = File.ReadAllText(jsonFilePath);
                var deserializedList = JsonConvert.DeserializeObject<List<BoolType>>(jsonFromFile);
                for (int i = 0; i < Items.Count; i++)
                {
                    Items[i].BoolValue = deserializedList[i].BoolValue;
                }
            }
            catch (Exception ex)
            {
            }
        }

        public void SaveToJsonFile()
        {
            try
            {
                JsonSerializer serializer = new JsonSerializer();
                string strFloats = JsonConvert.SerializeObject(this.ToList(), Formatting.Indented);
                File.WriteAllText(jsonFilePath, strFloats);
            }
            catch (Exception ex)
            {

            }
        }
        public void RegisterAction(Action<string, bool> act)
        {
            foreach (var item in Items)
            {
                item.boolTypeAction += act;
                act.Invoke(item.Name, item.BoolValue);
                item.boolSaveAction += SaveToJsonFile;
            }
               
        }
    }
}
